<template>
  <div class="user-management">
    <!-- 页面头部 -->
    <div class="page-header">
      <h1>用户管理</h1>
      <p class="subtitle">查看和管理所有用户信息</p>
    </div>

    <!-- 搜索和筛选 -->
    <el-card class="filter-card">
      <div class="filter-section">
        <div class="search-bar">
          <el-input
            v-model="searchQuery"
            placeholder="搜索用户昵称或邮箱"
            style="width: 300px"
            clearable
            @input="handleSearch"
          >
            <template #prefix>
              <el-icon><Search /></el-icon>
            </template>
          </el-input>
        </div>
        
        <div class="filter-controls">
          <el-select v-model="statusFilter" placeholder="状态筛选" style="width: 120px" @change="handleFilter">
            <el-option label="全部" value="" />
            <el-option label="正常" value="0" />
            <el-option label="禁用" value="1" />
          </el-select>
          
          <el-select v-model="genderFilter" placeholder="性别筛选" style="width: 120px" @change="handleFilter">
            <el-option label="全部" value="" />
            <el-option label="男" value="M" />
            <el-option label="女" value="F" />
            <el-option label="其他" value="O" />
          </el-select>
          
          <el-button type="primary" @click="refreshData">
            <el-icon><Refresh /></el-icon>
            刷新
          </el-button>
        </div>
      </div>
    </el-card>

    <!-- 用户列表 -->
    <el-card class="table-card">
      <el-table
        :data="users"
        v-loading="loading"
        stripe
        style="width: 100%"
        :default-sort="{ prop: 'createTime', order: 'descending' }"
      >
        <el-table-column prop="id" label="ID" width="80" sortable />
        
        <el-table-column label="头像" width="80">
          <template #default="scope">
            <el-avatar :src="scope.row.avatar" :alt="scope.row.nickname">
              {{ scope.row.nickname?.charAt(0) }}
            </el-avatar>
          </template>
        </el-table-column>
        
        <el-table-column prop="nickname" label="昵称" min-width="120" sortable />
        
        <el-table-column prop="email" label="邮箱" min-width="180" sortable />
        
        <el-table-column prop="gender" label="性别" width="80">
          <template #default="scope">
            <el-tag v-if="scope.row.gender === 'M'" type="primary" size="small">男</el-tag>
            <el-tag v-else-if="scope.row.gender === 'F'" type="danger" size="small">女</el-tag>
            <el-tag v-else type="info" size="small">其他</el-tag>
          </template>
        </el-table-column>
        
        <el-table-column prop="status" label="状态" width="100">
          <template #default="scope">
            <el-tag v-if="scope.row.status === 0" type="success" size="small">正常</el-tag>
            <el-tag v-else type="danger" size="small">封禁</el-tag>
          </template>
        </el-table-column>
        
        <el-table-column prop="createTime" label="注册时间" width="160" sortable>
          <template #default="scope">
            {{ formatTime(scope.row.createTime) }}
          </template>
        </el-table-column>
        
        <el-table-column prop="loginTime" label="最后登录" width="160" sortable>
          <template #default="scope">
            {{ formatTime(scope.row.loginTime) }}
          </template>
        </el-table-column>
        
        <el-table-column label="操作" width="200" fixed="right">
          <template #default="scope">
            <el-button
              type="primary"
              size="small"
              @click="viewUserDetail(scope.row)"
            >
              查看详情
            </el-button>
            
            <el-button
              v-if="scope.row.status === 0"
              type="warning"
              size="small"
              @click="toggleUserStatus(scope.row, 1)"
            >
              禁用
            </el-button>
            
            <el-button
              v-else
              type="success"
              size="small"
              @click="toggleUserStatus(scope.row, 0)"
            >
              启用
            </el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <div class="pagination-container">
        <el-pagination
          v-model:current-page="currentPage"
          v-model:page-size="pageSize"
          :page-sizes="[10, 20, 50, 100]"
          :total="total"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </el-card>

    <!-- 用户详情对话框 -->
    <el-dialog v-model="detailDialogVisible" title="用户详情" width="600px">
      <div v-if="selectedUser" class="user-detail">
        <div class="detail-header">
          <el-avatar :size="80" :src="selectedUser.avatar">
            {{ selectedUser.nickname?.charAt(0) }}
          </el-avatar>
          <div class="user-info">
            <h3>{{ selectedUser.nickname }}</h3>
            <p>{{ selectedUser.email }}</p>
          </div>
        </div>
        
        <el-descriptions :column="2" border>
          <el-descriptions-item label="用户ID">{{ selectedUser.id }}</el-descriptions-item>
          <el-descriptions-item label="性别">
            <el-tag v-if="selectedUser.gender === 'M'" type="primary" size="small">男</el-tag>
            <el-tag v-else-if="selectedUser.gender === 'F'" type="danger" size="small">女</el-tag>
            <el-tag v-else type="info" size="small">其他</el-tag>
          </el-descriptions-item>
          <el-descriptions-item label="生日">{{ selectedUser.birthday || '未设置' }}</el-descriptions-item>
          <el-descriptions-item label="状态">
            <el-tag v-if="selectedUser.status === 0" type="success">正常</el-tag>
            <el-tag v-else type="danger">封禁</el-tag>
          </el-descriptions-item>
          <el-descriptions-item label="注册时间" :span="2">
            {{ formatTime(selectedUser.createTime) }}
          </el-descriptions-item>
          <el-descriptions-item label="最后登录" :span="2">
            {{ formatTime(selectedUser.loginTime) }}
          </el-descriptions-item>
          <el-descriptions-item label="个人介绍" :span="2">
            {{ selectedUser.personalIntroduce || '暂无介绍' }}
          </el-descriptions-item>
        </el-descriptions>
      </div>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted } from 'vue';
import { ElMessage, ElMessageBox } from 'element-plus';
import { Search, Refresh } from '@element-plus/icons-vue';
import { getAllUsers, changeUserState } from '@/api/admin';

// 数据定义
const users = ref([]);
const loading = ref(false);
const currentPage = ref(1);
const pageSize = ref(20);
const total = ref(0);

// 搜索和筛选
const searchQuery = ref('');
const statusFilter = ref('');
const genderFilter = ref('');

// 对话框
const detailDialogVisible = ref(false);
const selectedUser = ref(null);

// 获取用户列表
const fetchUsers = async () => {
  loading.value = true;
  try {
    const params = {
      page: currentPage.value - 1, // 前端从1开始，后端从0开始
      size: pageSize.value,
      state: statusFilter.value ? parseInt(statusFilter.value) : undefined,
    };
    const response = await getAllUsers(params);
    users.value = response.content;
    total.value = response.totalElements;
  } catch (error) {
    ElMessage.error('获取用户列表失败');
  } finally {
    loading.value = false;
  }
};

// 搜索
const handleSearch = () => {
  // TODO: 实现搜索逻辑
  console.log('搜索:', searchQuery.value);
};

// 筛选
const handleFilter = () => {
  fetchUsers();
};

// 刷新数据
const refreshData = () => {
  fetchUsers();
};

// 分页处理
const handleSizeChange = (val: number) => {
  pageSize.value = val;
  fetchUsers();
};

const handleCurrentChange = (val: number) => {
  currentPage.value = val;
  fetchUsers();
};

// 查看用户详情
const viewUserDetail = (user: any) => {
  selectedUser.value = user;
  detailDialogVisible.value = true;
};

// 切换用户状态
const toggleUserStatus = async (user: any, newStatus: number) => {
  try {
    await ElMessageBox.confirm(
      `确定要${newStatus === 0 ? '启用' : '禁用'}用户 ${user.nickname} 吗？`,
      '确认操作',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
      }
    );

    // 调用API更新用户状态
    const response = await changeUserState({ userId: user.id, state: newStatus });
    console.log('切换用户状态响应:', response);
    if (response === "操作成功") {
      user.status = newStatus;
      ElMessage.success(`用户${newStatus === 0 ? '启用' : '禁用'}成功`);
    } else {
      ElMessage.error(response.message || '操作失败');
    }
  } catch (error) {
    // 用户取消操作或接口调用失败
    ElMessage.error('操作取消或失败');
  }
};

// 格式化时间
const formatTime = (time: string) => {
  if (!time) return '未知';
  return new Date(time).toLocaleString();
};

onMounted(() => {
  fetchUsers();
});
</script>

<style scoped>
.user-management {
  padding: 24px;
  background: #f5f7fa;
  min-height: 100vh;
}

.page-header {
  margin-bottom: 24px;
}

.page-header h1 {
  color: #2c3e50;
  font-size: 2rem;
  margin-bottom: 8px;
  font-weight: 600;
}

.subtitle {
  color: #7f8c8d;
  font-size: 1rem;
  margin: 0;
}

.filter-card {
  margin-bottom: 24px;
  border-radius: 12px;
}

.filter-section {
  display: flex;
  justify-content: space-between;
  align-items: center;
  flex-wrap: wrap;
  gap: 16px;
}

.filter-controls {
  display: flex;
  gap: 12px;
  align-items: center;
}

.table-card {
  border-radius: 12px;
  overflow: hidden;
}

.pagination-container {
  margin-top: 24px;
  display: flex;
  justify-content: center;
}

.user-detail {
  padding: 16px 0;
}

.detail-header {
  display: flex;
  align-items: center;
  margin-bottom: 24px;
  padding-bottom: 16px;
  border-bottom: 1px solid #ebeef5;
}

.user-info {
  margin-left: 16px;
}

.user-info h3 {
  margin: 0 0 8px 0;
  color: #2c3e50;
  font-size: 1.3rem;
}

.user-info p {
  margin: 0;
  color: #7f8c8d;
  font-size: 0.9rem;
}

:deep(.el-table) {
  border-radius: 8px;
}

:deep(.el-table th) {
  background-color: #fafafa;
  color: #606266;
  font-weight: 600;
}
</style>
